package craky.keeper;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;

import craky.keeper.remote.KeeperDBRemote;
import craky.keeper.util.DBUtil;

public class KeeperServer
{
    private static KeeperServer instance;

    private Server server;

    public static synchronized KeeperServer getInstance()
    {
        if(instance == null)
        {
            instance = new KeeperServer();
        }

        return instance;
    }

    private KeeperServer()
    {}

    public void start(int port)
    {
        start(port, null, true);
    }

    public Server start(int port, String dataParentPath, boolean join)
    {
        if(server == null || server.isStopped())
        {
            if(port < 1024 || port > 65535)
            {
                port = 30330;
            }

            try
            {
                DBUtil.createConnection(dataParentPath);
                server = new Server(port);
                ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
                context.setContextPath("/");
                server.setHandler(context);
                context.addServlet(KeeperDBRemote.class, "/Keeper");
                server.start();

                if(join)
                {
                    server.join();
                }
            }
            catch(Throwable t)
            {
                t.printStackTrace();

                try
                {
                    stop();
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }
            }
        }

        return server;
    }

    public void stop() throws Exception
    {
        if(server != null && server.isRunning())
        {
            DBUtil.closeConnection();
            server.stop();
            server.destroy();
        }

        server = null;
    }

    public boolean isRunning()
    {
        return server != null && server.isRunning();
    }

    public static void main(String...args) throws Exception
    {
        int port = 0;

        if(args != null && args.length > 0)
        {
            try
            {
                port = Integer.parseInt(args[0]);
            }
            catch(Exception e)
            {}
        }

        getInstance().start(port);
    }
}